package com.hd.quartz;

import com.hd.quartz.entity.ScheduleJobEntity;
import com.hd.quartz.service.ScheduleJobService;
import com.hd.quartz.util.ScheduleUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

/**
 * <h3>partitionjob</h3>
 * <p>QuartzPersistApplication</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2020-09-10 19:03
 **/
@SpringBootApplication
@MapperScan(basePackages = {"com.hd.quartz.dao"})
public class QuartzPersistApplication  implements CommandLineRunner{

    public static void main(String[] args) {
        SpringApplication.run(QuartzPersistApplication.class, args);
    }


    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ScheduleJobService scheduleJobService;

    @Override
    public void run(String... strings) throws Exception {
        List<ScheduleJobEntity> jobEntityList = scheduleJobService.list();
        for (ScheduleJobEntity entity : jobEntityList) {
            CronTrigger trigger = ScheduleUtils.getCronTrigger(scheduler, entity.getJobId());
            //如果不存在，则创建
            if(trigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, entity);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, entity);
            }
        }
    }
}
